<script setup>
import { ref, reactive, watch, onMounted, defineAsyncComponent, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { eventApi as MainApi, formById } from '@T2/service/api.ts';
import { useCurrentWatchStore, useIuserInfoStore } from '@T2/store/users.ts';

const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;
const iuserInfoStore = useIuserInfoStore();
const { info } = iuserInfoStore;

const show = ref(true);

const { currentFlow } = defineProps({
  currentFlow: {
    type: Object,
    required: true,
  }
});
const emits = defineEmits(['closed']);

onMounted(() => {
  init();
});
const Rt = reactive({
  firstNode: null,
  edge: null,
  nextNode: null,
  config: null,
});
const init = async () => {
  const { nodes, edges } = currentFlow?.fron_data || {};
  Rt.firstNode = nodes.find(i => i.type === 'first');
  if (!Rt.firstNode) {
    ElMessage.error('未知故障！');
    return;
  }
  Rt.edge = edges.find(i => i.sourceNodeId === Rt.firstNode.id);
  if (!Rt.edge) {
    ElMessage.error('未知故障！');
    return;
  }
  Rt.nextNode = nodes.find(i => i.id === Rt.edge.targetNodeId);
  const form = await getFormDetail(Rt.firstNode.properties.form);
  ElMessage.closeAll();
  Rt.config = form?.id ? JSON.parse(form.config) : null;
}
const getFormDetail = (id) => {
  if (!id) {
    return null;
  }
  return new Promise((resolve, reject) => {
    formById({
      method: 'get',
      id
    }).then(res => {
      resolve(res);
    }).catch(err => {
      resolve(err);
    });
  })
}

/* 异步加载组件 */
const mapLoading = {
  loadingComponent: {
    template: '<div>加载 A 中...</div>',
  },
  errorComponent: {
    template: '<div>加载失败</div>',
  },
  delay: 200,
  timeout: 5000,
};
const componentsMap = {
  input: defineAsyncComponent({
    loader: () => import('../plugin/edit/input.vue'),
    ...mapLoading,
  }),
  datetimePicker: defineAsyncComponent({
    loader: () => import('../plugin/edit/datetimePicker.vue'),
    ...mapLoading,
  }),
  select: defineAsyncComponent({
    loader: () => import('../plugin/edit/select/index.vue'),
    ...mapLoading,
  }),
  uploadImage: defineAsyncComponent({
    loader: () => import('../plugin/edit/uploadImage.vue'),
    ...mapLoading,
  }),
  uploadAttachment: defineAsyncComponent({
    loader: () => import('../plugin/edit/uploadAttachment.vue'),
    ...mapLoading,
  }),
  switch: defineAsyncComponent({
    loader: () => import('../plugin/edit/switch.vue'),
    ...mapLoading,
  }),
};
const getComponent = (item) => {
  return componentsMap[item.UDID] || null;
}

/* 新增编辑 */
const nameRf = ref(null);
const formChange = (item, value, showStr) => {
  item.value = value;
  if (showStr) {
    item.showStr = showStr;
  }
}
const handleMainSubmit = () => {
  if (Rt.config.find(item => item.required && !item.value) || !nameRf.value) {
    ElMessage.error('必填项未填写完整！');
    return;
  }
  AddMain();
}
const AddMain = () => {
  let obj = {};
  if (Rt.config) {
    const req = Rt.config.map(i => {
      let tp = {};
      if (i.sign) {
        tp.sign = i.sign;
      }
      if (i.showStr) {
        tp.showStr = i.showStr;
      }
      return { label: i.label, value: i.value, span: i.span, UDID: i.UDID, ...tp }
    });
    obj.request_params = JSON.stringify(req);
  }
  MainApi({
    method: 'post',
    data: {
      name: nameRf.value,
      create_user: info.id,
      project: curProject.id,
      flow: currentFlow.id,
      node: Rt.nextNode.properties.sql_id,
      status: Rt.nextNode.properties.status,
      ...obj,
    }
  }).then(res => {
    handleCancel(true);
    ElMessage.success('新增成功');
  }).catch(err => {
    handleCancel(true);
  });
}
const handleCancel = (refresh = false) => {
  emits('closed', refresh);
}

</script>

<template>
  
  <div>
    <el-drawer v-model="show" size="980" class="popup" @closed="handleCancel()">
      <template #header>
        <div class="title-name">新增信息</div>
      </template>
      <template #default>
        <div class="content-box flex flex-wrap">
          <div class="form-item flex--center" style="width: 50%">
            <p>
              <span class="isRequired">名称：</span>
            </p>
            <el-input v-model="nameRf"></el-input>
          </div>
          <template v-for="item in Rt.config">
            <div class="form-item flex--center" :style="{ width: `calc(${50 * item.span }% )`}">
              <p>
                <span :class="{ 'isRequired': item.required }">{{ item.label }}：</span>
              </p>
              <component
                :config="item"
                :is="getComponent(item)"
                @change="(value, showStr) => formChange(item, value, showStr)"
              />
            </div>
          </template>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="handleCancel()">取 消</el-button>
          <el-button type="primary" @click="handleMainSubmit()">确 定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
.popup .title-name{
  font-weight: 500;
  font-size: 20px;
  color: #252525;
}
.content-box {
  flex: 1;
  position: relative;
  align-content: flex-start;
}
.form-item {
  margin: 10px 0;
  padding: 0 10px;
  align-items: flex-start;
  p {
    width: 100px;
    min-width: 100px;
    height: 32px;
    line-height: 32px;
    text-align: right;
    white-space: nowrap;
    color: #6d6d6d;
    span {
      position: relative;
      &.isRequired::before {
        position: absolute;
        content: '*';
        left: -10px;
        top: 50%;
        transform: translateY(-50%);
        color: #ff0000;
      }
    }
  }
}
</style>

<style scoped>
:deep(.popup .el-drawer__header) {
  height: 60px;
  padding-bottom: 10px;
  margin-bottom: 0;
  border-bottom: 1px solid #EDEFF3;
}
:deep(.popup .el-drawer__body) {
  overflow: hidden;
  display: flex;
  padding: 20px 0;
}
:deep(.popup .el-form-item__content) {
  align-content: flex-start;  /* 不加这个文本域以及上传资料之后对不齐 */
}
</style>